package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RequestMapping("/admin/dish")
@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 添加餐品及口味
     * @param dishDTO
     * @return
     */
    @PostMapping
    public Result disAndFlavorInsert(@RequestBody DishDTO dishDTO) {
        log.info("添加数据{}", dishDTO);
        dishFlavorService.disAndFlavorInsert(dishDTO);
        String key = "dish_" + dishDTO.getCategoryId();
        cleanRedis(key);
        return Result.success();
    }

    /**
     * 菜品分页查询
     * @param
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        log.info("传递来的参数是{}",dishPageQueryDTO);
        PageResult pageResult = dishFlavorService.pageQuery(dishPageQueryDTO);
        return  Result.success(pageResult);
    }

    /**
     * 根据id删除菜品
     * @param ids
     */
    @DeleteMapping
    public Result deleteByIds(@RequestParam List<Long> ids) {
        log.info("传入的id是{}",ids);
        dishFlavorService.deleteByIds(ids);
        cleanRedis("dish_*");
        return Result.success();

    }

    /**
     * 根据id查询彩屏
     */
    @GetMapping("/{id}")
    public Result<DishVO> getById( @PathVariable Long id ) {
        log.info("要查询的id是{}",id);
        DishVO dishVO = dishFlavorService.getById(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品数据
     */
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品数据{}",dishDTO);
        dishFlavorService.update(dishDTO);
        cleanRedis("dish_*");
        return Result.success();
    }
    /**
     * 修改菜品起售停售状态
     */
    @PostMapping("/status/{status}")
    public Result startOrEnd(@PathVariable Integer status, Long id) {
        log.info("要修改的id是{},状态是{}",id,status);
        dishFlavorService.setStatus(status,id);
        cleanRedis("dish_*");
        return Result.success();
    }
    /**
     * 根据分类id查询菜品
     */
    @GetMapping("/list")
    public Result<List<Dish>> listGetById(Long categoryId) {
        log.info("根据分类id查询菜品{}",categoryId);
        List<Dish> list = dishFlavorService.listGetById(categoryId);
        return Result.success(list);
    }
    private void cleanRedis(String partten) {
        Set keys = redisTemplate.keys(partten);
        redisTemplate.delete(keys);
    }
}
